<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
*/
namespace core;
defined('BY_JYA') or exit('error');
class ks_pay{
	/*
		初始化接口参数
		如未传入接口参数，则自动从系统支付参数中获取
		
		参数介绍
		$config=array(
			'appid'=>'商户appid',
			'mch_id'=>'商户号',
			'sub_pay'=>'是否服务商支付',
			'sub_mch_id'=>'子商户号',
			'sub_appid'=>'子商户appid',
			'key'=>'商户支付密钥',
			'apiclient_cert'=>'证书cert文件绝对路径',
			'apiclient_key'=>'证书key文件绝对路径',
		);
	*/
	public function __construct($config=array()){
		if($config){
			$this->config=$config;
			if($config['id']){
			    $this->config=pdo_get('core_account_wxapp',array('id'=>$config['id'],'uniacid'=>$_SESSION['uniacid']));
			    $this->config['app_id']=$this->config['ks_appid'];
			    if($this->config['ksexpire']<TIMESTAMP){
        			$this->getAccessToken();
        		}
			}
		}else{
			$setting=uni_setting('pay');
			$this->config=array(
				'app_id'=>$setting['ks_appid'],
				'ks_secret'=>$setting['ks_secret'],
				'ks_paymchid'=>$setting['ks_paymchid'],
				'ks_paysecret'=>$setting['ks_paysecret'],
			);
		}
	}
	public function getAccessToken($continue=false){//获取access_token
		global $_AR;
		if($this->config['ksexpire']>TIMESTAMP && !$continue && $this->config['ttup_tokentime']<TIMESTAMP-600){
			return $this->config['ksaccess_token'];
		}
		if(!$this->config['ks_secret']){
			return false;
		}else{
			$url = "https://open.kuaishou.com/oauth2/access_token?app_id=".$this->config['app_id']."&app_secret=".$this->config['ks_secret']."&grant_type=client_credentials";
		}
		$post=json_encode(array('jy'=>1));
		$res=cfc('http')->ihttp_json($url,$post);
		if(is_error($res)){
			if($_SESSION['os']=='windows'){
				exi('快手小程序授权失败, 请稍后重试！错误详情：'.$content['message'],'error');
			}
		}
		$token = @json_decode($res['content'], true);
		if(empty($token) || $token['result']>1){
			if($_SESSION['os']=='windows'){
				exi('快手小程序授权失败, 请稍后重试！错误代码-' . $token['result'] . '，错误信息-' . $token['error_msg'],'error');
			}
		}
		$record = array('ttup_tokentime'=>TIMESTAMP);
		$record['ksaccess_token'] = $token['access_token'];
		$token['expires_in']=$token['expires_in']?:3600;
		$record['ksexpire'] = TIMESTAMP + $token['expires_in'] - 200;
		pdo_update('core_account_wxapp',$record,array('uniacid'=>$_SESSION['uniacid'],'id'=>$this->config['id']));
		$this->config['ksaccess_token']=$token['access_token'];
		return $token['access_token'];
	}
	/*
		小程序 支付，返回用于发起支付的数组
		参数介绍见 create_order 函数
	*/
	public function ksapp_pay($params){
		if($_SESSION['fromh5wxapp']==1 && $_SESSION['wxappopenid']){
			$params['openid']=$_SESSION['wxappopenid'];
		}else{
			$params['openid']=$_SESSION['openid'];
		}
		$res=$this->create_order($params);
		$package=array(
			'app_id'=>$params['appid']?:$this->config['app_id'],
			'timeStamp'=>"".TIMESTAMP,
			'orderinfo'=>$res['order_info'],
			'nonceStr'=>random(32),
			'signType'=>'MD5',
		);
		$package['sign']=$this->md5_sign($package);
		$package['msg_page']=$params['success_url'];
		return $package;
	}
	public function create_order($params){
		$api_url='https://open.kuaishou.com/openapi/mp/developer/epay/create_order';
		$package = array(
			'out_order_no'=>$params['tid'],
			'total_amount'=>round($params['fee']*100),
			'subject'=>$params['title'],
			'detail'=>$params['title'],
			'type'=>$this->config['ks_paygoodsid'],
			'expire_time'=>600,
			'notify_url'=>$params['notify_url']?:SITEROOT .'custom/payresult/kspay_notify.php?id=1',
			'open_id'=>$params['openid'],
		);
		$res=$this->request($api_url,$package);
		//快手小程序同步订单
		$updata['list'][]=array(
				'goodsid'=>$params['goodsid']?:108,
				'image'=>tomedia('../core/resource/images/welcomehdp02.jpg'),
				'title'=>$params['title'],
				'price'=>$params['fee'],
		);
		$updata['status']=0;
		$updata['price']=$params['fee'];
		$updata['detail_url']='core/member/credit_log/index';
		$updata['tid']=$params['tid'];
		$updata['open_id']=$params['openid'];
		$updata['createtime']=time();
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($res));
		//$this->push_order($updata);
		return $res;
	}
	//订单同步
	public function push_order($order=array()){
		$api_url='https://open.kuaishou.com/api/apps/order/v2/push';
		$item_list[]=array(
			'item_code'=>$order['list'][0]['goodsid'].'',
			'img'=>tomedia($order['list'][0]['image']),
			'title'=>$order['list'][0]['title'],
			'price'=>$order['list'][0]['price']*100,
		);
		$order_detail=array(
			'order_id'=>$order['tid'],
			'create_time'=>$order['createtime']*1000,
			'status'=>$order['status']?'已支付':'待支付',
			'amount'=>1,
			'total_price'=>$order['price']*100,
			'detail_url'=>$order['detail_url']?:'jy_weishop/order/list/index',
			'item_list'=>$item_list,
		);
		$order_detail=ijson_encode($order_detail);
		$openid=$order['open_id'];
		if(!$openid){
			$openid=pdo_getcolumn('core_fans',array('ttgid'=>$this->config['id'],'mid'=>$order['mid'],'type'=>8,'uniacid'=>$_SESSION['uniacid']),'openid');
		}
		$package = array(
			'app_name'=>'douyin',
			'order_detail'=>$order_detail,
			'order_status'=>$order['status'],
			'order_type'=>0,
			'update_time'=>time()*1000,
			'open_id'=>$openid,
		);
		$package['access_token']=$this->config['ksaccess_token'];
		$res=$this->request($api_url,$package);
		return $res;
	}
	/*
		申请退款
		POST https://open.kuaishou.com/api/apps/ecpay/v1/create_refund
	*/
	public function refund_pay($params){
		$api_url='https://open.kuaishou.com/api/apps/ecpay/v1/create_refund';
		$params['refund_fee']=$params['refund_fee']?:$params['fee'];
		$package = array(
			'app_id'=>$this->config['app_id'],
			'out_trade_no'=>$params['tid'],
			'out_refund_no'=>$params['refund_no'],
			'total_fee'=>round($params['fee']*100),
			'refund_amount'=>round($params['refund_fee']*100),
			'reason'=>$params['refund_desc'],
			'notify_url'=>$params['notify_url']?:SITEROOT .'custom/payresult/kspay_notify.php',
			'cp_extra'=>ijson_encode(array('uniacid'=>$_SESSION['uniacid'])),
		);
		return $this->request($api_url,$package,true);
	}
	/*
		发起接口请求
	*/
	private function request($api_url,$package,$ssl=false,$msg=''){
	    $package['app_id']=$this->config['app_id'];
		$package['sign']=$this->md5_sign($package);
		$package=ijson_encode($package);
		$api_url=$api_url.'?app_id='.$this->config['app_id'].'&access_token='.$this->config['ksaccess_token'];
		$res=cfc('http')->ihttp_json($api_url,$package);	
		if(is_error($res)){
			if($msg){
				return error($res['message']);
			}else{
				exi($res['message'].'，请联系管理员设置好参数！','error');
			}
		}
		$res=@json_decode($res['content'],true);
		if($res['result']>1){
			if($msg){
				return error($res['error_msg']);
			}else{
				exi($res['result'].$res['error_msg'].'，请联系管理员设置好参数！','error');
			}
		}
		return $res;
	}
	/*
		核对签名
	*/
	public function check_sign($params){
		$account=pdo_get('core_accounts',array('uniacid'=>$_SESSION['uniacid']));
		$msg_signature=$params['msg_signature'];
		$data=array();
		foreach($params as $k =>$v) {
			if ($k == "type" || $k == "sign" || $k == "msg_signature"){
				continue;
			}
			$data[]=$v;
		}
		$data[]=$account['token'];
		sort($data, SORT_STRING);
		$newsign=hash('sha1', join('', $data));
		if($newsign==$msg_signature){
			return true;
		}else{
			return false;
		}
	}
	/*
		生成签名
	*/
	private function md5_sign($map,$type=0){
		$rList = array();
		foreach($map as $k =>$v) {
			if ($k == "other_settle_params" || $k == "sign" || $k == "msg_signature" || $k == "thirdparty_id"){
				continue;
			}
			$value = trim(strval($v));
			$len = strlen($value);
			if ($len > 1 && substr($value, 0,1)=="\"" && substr($value,$len, $len-1)=="\""){
				$value = substr($value,1, $len-1);
			}
			$value = trim($value);
			if ($value == "" || $value == "null"){
				continue;
			}
			$rList[]=$k;
		}
		sort($rList, 2);
		$data='';
		foreach($rList as $i=>$k){
		    if($data){
		        $data.='&'.$k.'='.$map[$k]; 
		    }else{
		        $data.=$k.'='.$map[$k]; 
		    }
		}
		$data.=$this->config['ks_secret'];
		return md5($data);
	}
}